var Rx = require("rxjs");
var operators = require("rxjs/operators");
var SERVER_CONST = require("../server-const");
var express = require("express");
var router = express.Router();
var model = require("../model/accountModel");
var accountCat = model.accountCat;
var accountBudget = model.accountBudget;
var accountCatTitleStop = model.accountCatTitleStop;
var accountRecord = model.accountRecord;
var accountTitle = model.accountTitle;
var accountRelation = model.accountRelation;
var accountRelationStop = model.accountRelationStop;
var util = require("../server-util/util");
var mongoose = require("mongoose");
var subject = require("../subject");
const { next } = require("../subject");
const globalVar = require("../server-util/globalVar");
const moment = require("moment");
/* GET user listing. */
router.get("/", util.checkAuth, function (req, res, next) {
	res.send("respond with a resource");
});

//查询账目详情

router.get("/recordDetail", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.query.CreatorId);
	let recordId = mongoose.Types.ObjectId(req.query.recordId);
	accountRecord
		.aggregate([
			{
				$match: {
					CreatorId,
					_id: recordId,
				},
			},
			{
				$lookup: {
					from: "accounttitles",
					localField: "TitleId",
					foreignField: "_id",
					as: "Title",
				},
			},
			{
				$lookup: {
					from: "accountcats",
					localField: "CatId",
					foreignField: "_id",
					as: "Cat",
				},
			},
			{
				$lookup: {
					from: "accountrelations",
					localField: "AccountRelationPeopleId",
					foreignField: "_id",
					as: "AccountRelationPeoples",
				},
			},
			{
				$facet: {
					//这是没FileIds的 , 不需要做lookup处理
					emptyFileIds: [
						{
							$match: {
								FileIds: {
									$eq: null,
								},
							},
						},
					],
					//有FileIds的处理 , 可以用lookup
					notEmptyFileIds: [
						{
							$match: {
								FileIds: {
									$not: {
										$eq: null,
									},
								},
							},
						},
						{
							$lookup: {
								from: "files",
								let: {
									fileIds: {
										$map: {
											input: "$FileIds",
											as: "id",
											in: {
												$convert: {
													input: "$$id",
													to: "objectId",
												},
											},
										},
									},
								},
								pipeline: [
									{
										$match: {
											$expr: {
												$in: ["$_id", "$$fileIds"],
											},
										},
									},
								],
								as: "Files",
							},
						},
					],
				},
			},
			{
				$project: {
					data: {
						$concatArrays: ["$notEmptyFileIds", "$emptyFileIds"],
					},
				},
			}, //不显示 FileIds字段
			{
				$project: {
					first: {
						$slice: ["$data", 1],
					},
				},
			},
			{
				$unwind: "$first",
			},
			{
				$project: {
					"first.FileIds": 0,
				},
			},
			{
				$unwind: "$first.Cat",
			},
			{
				$unwind: "$first.Title",
			},
		])
		.exec(function (err, result) {
			if (err) {
				util.res.error({
					res,
					msg: "服务器报错",
				});
			} else {
				if (result && result[0] && result[0].first) {
					util.res.success({
						res,
						data: result[0].first,
					});
				} else {
					util.res.success({
						res,
						data: {},
					});
				}
			}
		});
});

//查询账目关联人

router.get("/accountRelation", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.query.CreatorId);
	accountRelation
		.aggregate([
			{
				$match: {
					$or: [
						{ CreatorId: CreatorId },
						{ DefineType: globalVar.DefineType.isSysDefault },
					],
				},
			},
			{
				$lookup: {
					from: "accountrelationstops",
					localField: "_id",
					foreignField: "AccountRelationId",
					as: "items",
				},
			},
			{
				$match: {
					items: {
						$size: 0,
					},
				},
			},
			{
				$project: {
					items: 0,
				},
			},
		])
		.exec(function (err, result) {
			if (err) {
				util.res.error({
					res,
					msg: "服务器报错",
				});
			} else {
				util.res.success({
					res,
					data: result,
				});
			}
		});
});

//删除账户关联人
router.post(
	"/removeAccountRelationPeople",
	util.checkAuth,
	function (req, res, next) {
		let CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
		let DefineType = req.body.DefineType;
		let AccountRelationId = mongoose.Types.ObjectId(req.body.AccountRelationId);
		let CreateAt = new Date().getTime();
		if (DefineType == globalVar.DefineType.isUserDefine) {
			accountRelation
				.deleteOne({
					CreatorId,
					_id: AccountRelationId,
					DefineType,
				})
				.exec(function (err, result) {
					if (err) {
						util.res.error({
							res,
							msg: err,
						});
					} else {
						util.res.success({
							res,
							data: result,
						});
					}
				});
		} else {
			new accountRelationStop({
				CreatorId,
				AccountRelationId,
				CreateAt,
			}).save(function (err, result) {
				if (err) {
					util.res.error({
						res,
						msg: err,
					});
				} else {
					util.res.success({
						res,
						data: result,
					});
				}
			});
		}
	}
);

//更新账户联系人
router.post(
	"/updateAccountRelationPeople",
	util.checkAuth,
	function (req, res, next) {
		let CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
		let _id = mongoose.Types.ObjectId(req.body._id);
		let Title = req.body.Title;
		let UpdateAt = new Date().getTime();
		accountRelation
			.update(
				{
					CreatorId,
					_id,
				},
				{
					$set: {
						Title,
						UpdateAt,
					},
				}
			)
			.exec(function (err, result) {
				if (err) {
					util.res.error({
						res,
						msg: err,
					});
				} else {
					util.res.success({
						res,
						data: result,
					});
				}
			});
	}
);

//新增账户关联人
router.post(
	"/addAccountRelationPeople",
	util.checkAuth,
	function (req, res, next) {
		let CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
		let Title = req.body.Title;
		let DefineType = globalVar.DefineType.isUserDefine;
		let Remark = req.body.Remark;
		let OrderNum = 0;
		let CreateAt = new Date().getTime();
		let UpdateAt = new Date().getTime();
		new accountRelation({
			Title,
			CreatorId,
			DefineType,
			Remark,
			CreateAt,
			UpdateAt,
			OrderNum,
		}).save(function (err, result) {
			if (err) {
				util.res.error({
					res,
					msg: err,
				});
			} else {
				util.res.success({
					res,
					data: result,
				});
			}
		});
	}
);

//搜索 cat 或者 title
router.get("/str", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.query.CreatorId);
	//输入的字符
	let w = req.query.w;
	let accountRecordType = req.query.accountRecordType;

	let query = {};
	if (accountRecordType != null || accountRecordType != undefined) {
		let bool = accountRecordType == "true" ? true : false;
		query = {
			$match: {
				AccountType: bool,
			},
		};
	}

	var parr = [
		//先是 cat
		new Promise((resolve, reject) => {
			accountCat
				.aggregate([
					{
						$match: {
							$or: [
								{ CreatorId: CreatorId },
								{ DefineType: globalVar.DefineType.isSysDefault },
							],
						},
					},
					{
						$match: {
							TypeName: {
								$regex: new RegExp(w, "i"),
							},
						},
					},
					query,
				])
				.exec((err, result) => {
					if (err) {
						reject(err);
					} else {
						resolve(result);
					}
				});
		}),
		//再是 title
		new Promise((resolve, reject) => {
			accountTitle
				.aggregate([
					{
						$match: {
							$or: [
								{ CreatorId: CreatorId },
								{ DefineType: globalVar.DefineType.isSysDefault },
							],
						},
					},
					{
						$match: {
							TitleName: {
								$regex: new RegExp(w, "i"),
							},
						},
					},
					query,

					{
						$lookup: {
							from: "accountcats",
							localField: "CatId",
							foreignField: "_id",
							as: "cats",
						},
					},

					{
						$project: {
							_id: "$_id",
							CatType: "$CatType",
							TitleName: "$TitleName",
							CreateAt: "$CreateAt",
							UpdateAt: "$UpdateAt",
							OrderNum: "$OrderNum",
							DefineType: "$DefineType",
							IconPath: "$IconPath",
							isDefaultSelect: "$isDefaultSelect",
							AccountType: "$AccountType",
							CatId: "$CatId",
							__v: "$__v",
							cat: {
								$arrayElemAt: ["$cats", 0],
							},
						},
					},
				])
				.exec((err, result) => {
					if (err) {
						reject(err);
					} else {
						resolve(result);
					}
				});
		}),
	];

	Promise.all(parr)
		.then((result) => {
			util.res.success({
				res,
				data: result,
			});
		})
		.catch((err) => {
			util.res.error({
				res,
				msg: err,
			});
		});
});

//初始化分类和标题列表，返回给前台
//MaxCustomTitleLen 显示自定义标题 为null 显示全部
//MaxCustomCatsLen 显示自定义分类 为null 显示全部
//MaxSystemTitleLen 显示系统标题 为null 显示全部
router.get("/titlesAndCats", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.query.CreatorId);

	//自定义title，最多显示几个
	let MaxCustomTitleLen = req.query.MaxCustomTitleLen
		? req.query.MaxCustomTitleLen
		: null;
	//自定义cat,最多显示几个
	let MaxCustomCatsLen = req.query.MaxCustomCatsLen
		? req.query.MaxCustomCatsLen
		: null;
	//系统title,最多显示几个
	let MaxSystemTitleLen = req.query.MaxSystemTitleLen
		? req.query.MaxSystemTitleLen
		: null;

	let AccountType = null;
	let match = {
		$match: {
			$or: [
				{
					CreatorId,
				},
				{
					DefineType: globalVar.DefineType.isSysDefault,
				},
			],
		},
	};
	if (req.query.AccountType != null) {
		AccountType = req.query.AccountType;
		match.$match.AccountType = AccountType == "true" ? true : false;
	}

	new Rx.Observable((ob) => {
		accountCat
			.aggregate([
				{
					...match,
				},
				{
					$sort: {
						CreateAt: -1,
					},
				},
			])
			.exec(function (err, result) {
				result = result.reduce((p, c, ci) => {
					//系统cat，全显示
					if (c.DefineType == globalVar.DefineType.isSysDefault) {
						p.push(c);
					}
					//自定义cat
					else {
						var len = p.filter((a) => {
							return a.DefineType == globalVar.DefineType.isUserDefine;
						}).length;
						if (MaxCustomCatsLen != null && len < MaxCustomCatsLen) {
							p.push(c);
						} else if (MaxCustomCatsLen == null) {
							p.push(c);
						}
					}

					return p;
				}, []);

				if (err) {
					ob.error(error);
					ob.complete();
				} else {
					ob.next(result);
				}
			});
	})
		.pipe(
			operators.concatMap((prev) => {
				return new Rx.Observable((ob) => {
					accountTitle
						.aggregate([
							{
								...match,
							},
							{
								$sort: {
									isDefaultSelect: -1,
								},
							},
						])
						.exec((error, result) => {
							result = result.reduce((p, c, ci) => {
								//系统title，不显示
								if (c.DefineType == globalVar.DefineType.isSysDefault) {
									var len = p.filter((a) => {
										return a.DefineType == globalVar.DefineType.isSysDefault;
									}).length;
									if (MaxSystemTitleLen != null && len < MaxSystemTitleLen) {
										p.push(c);
									} else if (MaxSystemTitleLen == null) {
										p.push(c);
									}
								}
								//自定义title
								else {
									var len = p.filter((a) => {
										return a.DefineType == globalVar.DefineType.isUserDefine;
									}).length;
									if (MaxCustomTitleLen != null && len < MaxCustomTitleLen) {
										p.push(c);
									} else if (MaxCustomTitleLen == null) {
										p.push(c);
									}
								}

								return p;
							}, []);

							if (error) {
								ob.error(error);
								ob.complete();
							} else {
								ob.next({
									cats: prev,
									titles: result,
								});
							}
						});
				});
			}),

			//过滤掉停用的cat和title
			operators.concatMap((data) => {
				return new Rx.Observable((ob) => {
					//注意这里会过滤掉用户停用的cat , 如果停用了 ,前台一定要把默认选中的title给重新赋值
					accountCatTitleStop
						.aggregate([
							{
								$match: {
									CreatorId,
								},
							},
						])
						.exec((err, rdata) => {
							if (err) {
								ob.error(err);
								ob.complete();
							} else {
								if (rdata.length > 0) {
									data.cats = data.cats.filter((cf) => {
										return rdata.every((sf) => {
											if (!sf.CatId) return true;
											return sf.CatId.toString() != cf._id.toString();
										});
									});
									data.titles = data.titles.filter((cf) => {
										return rdata.every((sf) => {
											if (!sf.TitleId) return true;
											return sf.TitleId.toString() != cf._id.toString();
										});
									});
								}
								ob.next(data);
								ob.complete();
							}
						});
				});
			})
		)
		.subscribe((sres) => {
			util.res.success({
				res,
				data: sres,
			});
		});
});

/**
 * @api {GET} /account/titles 查询账户标题
 * @apiSampleRequest off
 * @apiParam (params) {String} UserId
 * @apiGroup account
 */
router.get("/titles", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.query.CreatorId);
	accountTitle
		.aggregate([
			{
				$match: {
					$or: [
						{
							CreatorId,
						},
						{
							DefineType: globalVar.DefineType.isSysDefault,
						},
					],
				},
			},
		])
		.exec(function (err, result) {
			if (err) {
				util.res.error({
					res,
					msg: "服务器报错",
				});
			} else {
				util.res.success({
					res,
					data: result,
				});
			}
		});
});
//新增预算
router.post("/budget/add", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
	let CreateAt = new Date().getTime();
	let budgetMonth = req.body.budgetMonth
		? req.body.budgetMonth
		: new Date().getTime();
	let budget = req.body.budget ? req.body.budget : "0";
	let Remark = req.body.Remark ? req.body.Remark : "";
	let UpdateAt = null;
	accountBudget
		.update(
			//查询CreatorId,budgetMonth,没有则新增
			{
				CreatorId,
				budgetMonth,
			},
			{
				//需要更新
				$set: {
					Remark,
					UpdateAt,
					budget,
				},
				//有则不更新
				$setOnInsert: {
					CreatorId,
					CreateAt,
					budgetMonth,
				},
			},

			{
				//没有则新增
				upsert: true,
			}
		)
		.exec(function (err, result) {
			if (err) {
				util.res.error({
					res,
					msg: err,
				});
			} else {
				util.res.success({
					res,
					data: result,
				});
			}
		});
});

// 本月预算剩余 只做本月预算剩余用,不要拿来查询时间段内的收入和支出.
// 注意,dateRange传一个月的开始和结束日期,不要跨月
router.post(
	"/budget/budgetBalanceOfMonth",
	util.checkAuth,
	function (req, res, next) {
		let CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
		//传时间戳字符串
		let dateRange = req.body.dateRange;
		var start = dateRange[0];
		var end = dateRange[1];
		var budgetMonth = req.body.budgetMonth;

		new Rx.Observable((ob) => {
			let CreateAt = {
				$gte: start,
				$lte: end,
			};
			accountRecord
				.aggregate([
					{
						$match: {
							CreateAt,
							CreatorId,
						},
					},
					{
						$group: {
							_id: "$AccountType",
							total: {
								$sum: "$Money",
							},
						},
					},
				])
				.exec((err, result) => {
					if (err) {
						ob.error(err);
						ob.complete();
					} else {
						ob.next(result);
					}
				});
		})
			.pipe(
				operators.concatMap((prev) => {
					return new Rx.Observable((ob) => {
						var pay = 0;

						if (
							prev.find((r) => {
								return r._id == false;
							})
						) {
							pay = prev.find((r) => {
								return r._id == false;
							}).total;
						}
						var income = 0;
						if (
							prev.find((r) => {
								return r._id == true;
							})
						) {
							income = prev.find((r) => {
								return r._id == true;
							}).total;
						}
						accountBudget
							.aggregate([
								{
									$match: {
										budgetMonth,
										CreatorId,
									},
								},
							])
							.exec((err, result) => {
								if (err) {
									ob.error(err);
									ob.complete();
								} else {
									let budget = 0;
									if (result && result[0] && Number(result[0].budget)) {
										budget = Number(result[0].budget);
									} else {
										budget = "";
									}

									ob.next({
										budget,
										pay,
										income,
										budgetMonth: budgetMonth,
									});
								}
							});
					});
				})
			)
			.subscribe(
				(result) => {
					util.res.success({
						res,
						data: result,
					});
				},
				(error) => {
					util.res.error({
						res,
						msg: error,
					});
				}
			);
	}
);

//查询预算 , 只查预算设置 , 没有算当月的收入和支出
router.get("/budget", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.query.CreatorId);
	let budgetMonth = req.query.budgetMonth;
	let Remark = req.query.Remark;
	let budget = req.query.budget;
	let match = {
		$match: {
			CreatorId,
		},
	};
	if (budgetMonth) {
		match.$match["budgetMonth"] = budgetMonth;
	}
	if (Remark) {
		match.$match["Remark"] = Remark;
	}
	if (budget) {
		match.$match["budget"] = budget;
	}
	accountBudget.aggregate([match]).exec(function (err, result) {
		if (err) {
			util.res.error({
				res,
				msg: "服务器报错",
			});
		} else {
			util.res.success({
				res,
				data: result,
			});
		}
	});
});

/**
 * @api {GET} /account/cats 查询账户分类
 * @apiSampleRequest off
 * @apiParam (params) {String} UserId
 * @apiGroup account
 */
router.get("/cats", util.checkAuth, function (req, res, next) {
	let UserId = mongoose.Types.ObjectId(req.query.UserId);
	accountCat
		.aggregate([
			{
				$match: {
					$or: [
						{
							CreatorId: UserId,
						},
						{
							DefineType: globalVar.DefineType.isSysDefault,
						},
					],
				},
			},
			{
				$sort: {
					CreateAt: -1,
				},
			},
		])
		.exec(function (err, result) {
			if (err) {
				util.res.error({
					res,
					msg: "服务器报错",
				});
			} else {
				util.res.success({
					res,
					data: result,
				});
			}
		});
});

/**
 * @api {POST} /account/addCat 新增分类
 * @apiSampleRequest off
 * @apiParam (params) {Number} AccountType 账户类型 0 收入 1 支出
 * @apiParam (params) {String} TypeName 类目名称
 * @apiParam (params) {String} OrderNum 排序序号
 * @apiParam (params) {String} CreatorId 创建人id
 * @apiGroup account
 */

router.post("/addCat", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
	let AccountType = req.body.AccountType == "true" ? true : false;
	let TypeName = req.body.TypeName;
	let CreateAt = new Date().getTime();
	let UpdateAt = null;
	let OrderNum = 0;
	let IconPath = req.body.IconPath;

	new accountCat({
		CreatorId,
		AccountType: AccountType,
		TypeName,
		CreateAt,
		UpdateAt,
		OrderNum,
		IconPath,
	}).save(function (err, result) {
		if (err) {
			util.res.error({
				res,
				msg: err,
			});
		} else {
			util.res.success({
				res,
				data: result,
			});
		}
	});
});

/**
 * @api {POST} /account/addTitle 新增账户标题
 * @apiSampleRequest off
 * @apiParam (params) {String} UserId
 * @apiParam (params) {String} UserId
 * @apiGroup account
 */
router.post("/addTitle", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
	let AccountType = req.body.AccountType;
	let CatType = req.body.CatType;
	let CatId = req.body.CatId;
	let TitleName = req.body.TitleName;
	let CreateAt = new Date().getTime();
	let UpdateAt = null;
	let OrderNum = 0;
	let IconPath = req.body.IconPath;

	new accountTitle({
		CreatorId,
		AccountType,
		CatType,
		CatId,
		TitleName,
		CreateAt,
		UpdateAt,
		OrderNum,
		IconPath,
	}).save(function (err, result) {
		if (err) {
			util.res.error({
				res,
				msg: "服务器报错",
			});
		} else {
			util.res.success({
				res,
				data: result,
			});
		}
	});
});

//更新title
router.post("/updateTitle", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
	let _id = mongoose.Types.ObjectId(req.body._id);
	let TitleName = req.body.TitleName;
	let IconPath = req.body.IconPath;
	let CatType = req.body.CatType;
	let CatId = mongoose.Types.ObjectId(req.body.CatId);
	let UpdateAt = new Date().getTime();

	new Rx.Observable((ob) => {
		accountTitle
			.aggregate([
				{
					$match: {
						_id,
					},
				},
			])
			.exec(function (error, result) {
				if (
					result &&
					result[0] &&
					result[0].DefineType != globalVar.DefineType.isSysDefault
				) {
					ob.next(true);
					ob.complete();
				} else {
					ob.error(false);
					ob.complete();
				}
			});
	})
		.pipe(
			operators.concatMap((result) => {
				return new Rx.Observable((ob) => {
					if (result) {
						accountTitle
							.update(
								//查询的字段
								{
									CreatorId,
									_id,
								},
								//需要更新的字段
								{
									$set: {
										TitleName,
										IconPath,
										UpdateAt,
										CatType,
										CatId,
									},
								}
							)
							.exec(function (err, result) {
								if (err) {
									ob.error(err);
									ob.complete();
								} else {
									ob.next();
									ob.complete;
								}
							});
					} else {
						ob.error(err);
						ob.complete();
					}
				});
			})
		)
		.subscribe(
			(result) => {
				accountTitle
					.aggregate([
						{
							$match: {
								_id,
							},
						},
					])
					.exec(function (err, result) {
						if (err) {
							util.res.error({
								res,
								msg: err,
							});
						} else {
							util.res.success({
								res,
								data: result[0],
							});
						}
					});
			},
			(err) => {
				util.res.error({
					res,
					msg: err,
				});
			}
		);
});

//更新cat
router.post("/updateCat", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
	let _id = mongoose.Types.ObjectId(req.body._id);
	let TypeName = req.body.TypeName;
	let IconPath = req.body.IconPath;
	let UpdateAt = new Date().getTime();

	new Rx.Observable((ob) => {
		accountCat
			.aggregate([
				{
					$match: {
						_id,
					},
				},
			])
			.exec(function (error, result) {
				if (
					result &&
					result[0] &&
					result[0].DefineType != globalVar.DefineType.isSysDefault
				) {
					ob.next(true);
					ob.complete();
				} else {
					ob.error(false);
					ob.complete();
				}
			});
	})
		.pipe(
			operators.concatMap((result) => {
				return new Rx.Observable((ob) => {
					if (result) {
						accountCat
							.update(
								//查询的字段
								{
									CreatorId,
									_id,
								},
								//需要更新的字段
								{
									$set: {
										TypeName,
										IconPath,
										UpdateAt,
									},
								}
							)
							.exec(function (err, result) {
								if (err) {
									ob.error(err);
									ob.complete();
								} else {
									ob.next();
									ob.complete;
								}
							});
					} else {
						ob.error(false);
						ob.complete();
					}
				});
			})
		)
		.subscribe(
			(result) => {
				accountCat
					.aggregate([
						{
							$match: {
								_id,
							},
						},
					])
					.exec(function (err, result) {
						if (err) {
							util.res.error({
								res,
								msg: err,
							});
						} else {
							util.res.success({
								res,
								data: result[0],
							});
						}
					});
			},
			(err) => {
				util.res.error({
					res,
					msg: err,
				});
			}
		);
});

//更新记录
router.post("/updateAccountRecord", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
	let _id = mongoose.Types.ObjectId(req.body._id);
	let AccountType = req.body.AccountType;
	let CatId = !!req.body.CatId ? mongoose.Types.ObjectId(req.body.CatId) : null;
	let TitleId = !!req.body.TitleId
		? mongoose.Types.ObjectId(req.body.TitleId)
		: null;
	let Place = req.body.Place;
	let Remark = req.body.Remark;
	let TitleName = req.body.TitleName;
	let Money = req.body.Money;
	let IconPath = req.body.IconPath;
	let CreateAt = new Date().getTime();
	let UpdateAt = null;
	let OrderNum = 0;
	accountRecord
		.update(
			//查询CreatorId,budgetMonth,没有则新增
			{
				CreatorId,
				AccountType,
				_id,
			},
			{
				//需要更新
				$set: {
					CatId,
					TitleId,
					UpdateAt,
					Place,
					Remark,
					TitleName,
					Money,
					IconPath,
					OrderNum,
				},
			}
		)
		.exec(function (err, result) {
			if (err) {
				util.res.error({
					res,
					msg: err,
				});
			} else {
				accountRecord
					.aggregate([
						{
							$match: {
								_id,
							},
						},
					])
					.exec(function (err, result) {
						if (err) {
							util.res.error({
								res,
								msg: err,
							});
						} else {
							util.res.success({
								res,
								data: result[0],
							});
						}
					});
			}
		});
});

/**
 * @api {POST} /account/addAccountRecord 新增一条记账记录
 */
router.post("/addAccountRecord", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
	let AccountType = req.body.AccountType;
	let CatId = !!req.body.CatId ? mongoose.Types.ObjectId(req.body.CatId) : null;
	//账目关联人
	let AccountRelationPeopleId = !!req.body.AccountRelationPeopleId
		? mongoose.Types.ObjectId(req.body.AccountRelationPeopleId)
		: null;
	let FileIds = !!req.body.FileIds ? req.body.FileIds : null;
	let TitleId = !!req.body.TitleId
		? mongoose.Types.ObjectId(req.body.TitleId)
		: null;
	let Place = req.body.Place;
	let Remark = req.body.Remark;
	let TitleName = req.body.TitleName;
	let Money = req.body.Money;
	let IconPath = req.body.IconPath;
	let CreateAt = new Date().getTime();

	if (!!req.body.Date) {
		CreateAt = req.body.Date;
	}
	let UpdateAt = null;
	let OrderNum = 0;

	new accountRecord({
		FileIds,
		CreatorId,
		AccountType,
		CatId,
		TitleId,
		Place,
		Money,
		CreateAt,
		UpdateAt,
		OrderNum,
		TitleName,
		Remark,
		IconPath,
		AccountRelationPeopleId,
	}).save(function (err, result) {
		if (err) {
			util.res.error({
				res,
				msg: "服务器报错",
			});
		} else {
			util.res.success({
				res,
				data: result,
			});
		}
	});
});

/**
 * @api {POST} /account/getAccountRecord 查找account记录
 */
router.post("/getAccountRecord", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
	//账户关联人id
	let AccountRelationPeopleId = null;
	if (
		req.body.AccountRelationPeopleId != null &&
		req.body.AccountRelationPeopleId != undefined
	) {
		AccountRelationPeopleId = mongoose.Types.ObjectId(
			req.body.AccountRelationPeopleId
		);
	}
	let AccountType = null;
	if (req.body.AccountType !== null && req.body.AccountType !== undefined) {
		switch (req.body.AccountType) {
			case globalVar.accountTypeLabel.INCOME: {
				AccountType = true;
				break;
			}
			case globalVar.accountTypeLabel.PAY: {
				AccountType = false;
				break;
			}
			case globalVar.accountTypeLabel.ACCOUNT_TYPE_ALL: {
				AccountType = null;
				break;
			}
		}
	}

	console.log(AccountType);

	let pageNum = parseInt(req.body.pageNum - 1);
	let pageSize = parseInt(req.body.pageSize);
	let w = req.body.w;
	//是搜索 , 还是获取记录
	let getAccountRecordType = req.body.getAccountRecordType
		? req.body.getAccountRecordType
		: globalVar.get_account_record_type.ACCOUNT_RECORD_GET;
	//传入时间戳
	let dateRange = req.body.dateRange;

	var match = {
		$match: {
			CreatorId,
		},
	};

	if (AccountType !== null && AccountType !== undefined) {
		match["$match"]["AccountType"] = AccountType;
	}

	if (
		AccountRelationPeopleId !== null &&
		AccountRelationPeopleId !== undefined
	) {
		match["$match"]["AccountRelationPeopleId"] = AccountRelationPeopleId;
	}
	if (!!dateRange) {
		let startDate = dateRange[0];
		let endDate = dateRange[1];
		match["$match"]["CreateAt"] = {
			$lte: endDate,
			$gte: startDate,
		};
	}

	var addField = {};

	if (!!w) {
		addField = {
			$addFields: {
				MoneyStr: {
					$convert: {
						input: "$Money",
						to: "string",
					},
				},
			},
		};
		match.$match["$or"] = [
			{ TitleName: { $regex: new RegExp(w, "ig") } },
			{ MoneyStr: { $regex: new RegExp(w, "ig") } },
			{ Remark: { $regex: new RegExp(w, "ig") } },
			{ Place: { $regex: new RegExp(w, "ig") } },
		];
	}

	let aggregate = [
		match,
		{
			$addFields: {
				dateTime: {
					$convert: {
						input: "$CreateAt",
						to: "double",
					},
				},
			},
		},
		{
			$sort: {
				dateTime: -1,
			},
		},
		{
			$lookup: {
				from: "accountrelations",
				localField: "AccountRelationPeopleId",
				foreignField: "_id",
				as: "AccountRelationPeoples",
			},
		},
		{
			$group: {
				_id: null,
				data: {
					$push: "$$ROOT",
				},
			},
		},
		{
			$project: {
				count: {
					$size: "$data",
				},
				data: 1,
			},
		},
		{
			$unwind: "$data",
		},
		{
			$skip: pageNum * pageSize,
		},
		{
			$limit: pageSize,
		},
		{
			$group: {
				_id: "$count",
				data: {
					$push: "$$ROOT",
				},
			},
		},

		{
			$project: {
				_id: 0,
				count: "$_id",
				data: "$data.data",
			},
		},
		{
			$facet: {
				emptyFileIds: [
					{
						$match: {
							$or: [
								{
									FileIds: {
										$eq: null,
									},
								},
							],
						},
					},
				],
				notEmptyFileIds: [
					{
						$match: {
							FileIds: {
								$not: {
									$eq: null,
								},
							},
						},
					},
					{
						$lookup: {
							from: "files",
							let: {
								fileIds: {
									$map: {
										input: "$FileIds",
										as: "id",
										in: {
											$convert: {
												input: "$$id",
												to: "objectId",
											},
										},
									},
								},
							},
							pipeline: [
								{
									$match: {
										$expr: {
											$in: ["$_id", "$$fileIds"],
										},
									},
								},
							],
							as: "Files",
						},
					},
				],
			},
		},
		{
			$project: {
				data: {
					$concatArrays: ["$notEmptyFileIds", "$emptyFileIds"],
				},
			},
		},
		{
			$project: {
				"data.FileIds": 0,
			},
		},
	];

	if (addField.hasOwnProperty("$addFields")) {
		aggregate.unshift(addField);
	}

	//分页
	new Rx.Observable((ob) => {
		accountRecord.aggregate(aggregate).exec(function (err, result) {
			let responseData = null;

			if (
				result &&
				Array.isArray(result) &&
				result.length > 0 &&
				result[0].data &&
				Array.isArray(result[0].data) &&
				result[0].data.length > 0
			) {
				let data = JSON.parse(JSON.stringify(result[0].data));
				delete result[0].data;
				result[0].data = JSON.parse(JSON.stringify(data[0].data));
				result[0].count = data[0].count;
				responseData = result[0];
			} else {
				responseData = {
					data: [],
					count: 0,
				};
			}
			setTimeout(()=>{
				if (err) {
					ob.error(err);
					ob.complete();
				} else {
					ob.next(responseData);
					ob.complete();
				}
			},2000)
		});
	})

		//求和，分别计算收入和支出的和
		.pipe(
			operators.concatMap((result) => {
				return new Rx.Observable((ob) => {
					let pageData = result;
					accountRecord
						.aggregate([
							match,
							{
								$group: {
									_id: {
										accountType: "$AccountType",
									},
									totalMoney: {
										$sum: "$Money",
									},
								},
							},
						])
						.exec((error, sumResult) => {
							if (error) {
								ob.error(error);
								ob.complete();
							} else {
								ob.next({
									pageData,
									totalCount: sumResult,
								});
								ob.complete();
							}
						});
				});
			})
		)
		.subscribe(
			(result) => {
				try {
					let rows = result.pageData.data;
					let total = result.pageData.count;
					let incomeMoney = Number(0) + "";
					let payMoney = Number(0) + "";
					if (
						result.hasOwnProperty("totalCount") &&
						Array.isArray(result.totalCount)
					) {
						let _incomeMoney = result.totalCount.find((res) => {
							return res._id.accountType == true;
						});
						if (_incomeMoney != null) {
							incomeMoney = Number(_incomeMoney.totalMoney) + "";
						}

						let _payMoney = result.totalCount.find((res) => {
							return res._id.accountType == false;
						});
						if (_payMoney != null) {
							payMoney = Number(_payMoney.totalMoney) + "";
						}
					}
					setTimeout(() => {
						util.res.success({
							res,
							data: {
								rows,
								total,
								incomeMoney,
								payMoney,
							},
						});
					}, 3000);
				} catch (err) {
					util.res.success({
						res,
						data: null,
					});
				}
			},
			(error) => {
				util.res.error({
					res,
					msg: "服务器报错",
				});
			}
		);
});
//todo 此接口废弃
//合计 收入 支出
router.post("/userTotalCalculation", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
	let timeRange = req.body.timeRange;
	var start = new Date(timeRange[0]).getTime() + "";
	var end = new Date(timeRange[1]).getTime() + "";
	let pageNum = parseInt(req.body.pageNum - 1);
	let pageSize = parseInt(req.body.pageSize);

	let CreateAt = {
		$gte: start,
		$lte: end,
	};

	if (start == end) {
		CreateAt = {
			$eq: start,
		};
	}

	accountRecord
		.aggregate([
			{
				$match: {
					CreateAt,
					CreatorId,
				},
			},
			{
				$sort: {
					CreateAt: -1,
				},
			},
			{
				$facet: {
					metadata: [
						{
							$count: "total",
						},
						{
							$addFields: {
								pageNum,
								pageSize,
							},
						},
					],
					data: [
						{
							$skip: pageNum * pageSize,
						},
						{
							$limit: pageSize,
						},
					],
				},
			},
		])
		.exec((err, result) => {
			if (err) {
				util.res.error({
					res,
					msg: "服务器报错",
				});
			} else {
				util.res.success({
					res,
					data: result,
				});
			}
		});
});
//时间段内的收入和支出
router.post("/dateRangeBalance", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
	let dateRange = req.body.dateRange;
	var start = new Date(dateRange[0]).getTime() + "";
	var end = new Date(dateRange[1]).getTime() + "";

	let CreateAt = {
		$gte: start,
		$lte: end,
	};
	accountRecord
		.aggregate([
			{
				$match: {
					CreateAt,
					CreatorId,
				},
			},
			{
				$group: {
					_id: "$AccountType",
					total: {
						$sum: "$Money",
					},
				},
			},
		])
		.exec((err, result) => {
			var income = 0;
			var pay = 0;
			try {
				if (result && Array.isArray(result) && result.length > 0) {
					income = result.find((rf) => {
						return rf._id == true;
					}).total;

					pay = result.find((rf) => {
						return rf._id == false;
					}).total;
				}
			} catch (e) {
				util.res.error({
					res,
					msg: e,
				});
			}

			if (err) {
				util.res.error({
					res,
					msg: "服务器报错",
				});
			} else {
				util.res.success({
					res,
					data: {
						income,
						pay,
					},
				});
			}
		});
});

/* 删除一条记录 */
router.delete("/remove", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.param("CreatorId"));
	let _id = mongoose.Types.ObjectId(req.param("_id"));

	accountRecord
		.deleteOne({
			CreatorId,
			_id,
		})
		.exec(function (err, result) {
			if (!err) {
				util.res.success({
					res,
					data: result,
				});
			} else {
				util.res.error({
					res,
					msg: err,
				});
			}
		});
});

//停用cat或者title
router.post("/stop", util.checkAuth, function (req, res, next) {
	let CreatorId = mongoose.Types.ObjectId(req.body.CreatorId);
	//let CatId = mongoose.Types.ObjectId(req.body.CatId);
	//let TitleId = mongoose.Types.ObjectId(req.body.TitleId);
	let CreateAt = new Date().getTime();

	let type = {};

	if (req.body.CatId) {
		type = {
			Type: globalVar.TypeOfCatOrTitleStop.CAT,
			CatId: mongoose.Types.ObjectId(req.body.CatId),
		};
	} else if (req.body.TitleId) {
		type = {
			Type: globalVar.TypeOfCatOrTitleStop.TITLE,
			TitleId: mongoose.Types.ObjectId(req.body.TitleId),
		};
	}

	new Rx.Observable((ob) => {
		accountCatTitleStop.insertMany(
			[
				{
					CreatorId,
					...type,
					CreateAt,
				},
			],
			function (err, result) {
				if (!err) {
					ob.next({
						...result[0]._doc,
						stop: type,
					});
					ob.complete();
				} else {
					ob.error(err);
					ob.next();
				}
			}
		);
	})
		.pipe(
			operators.concatMap((data) => {
				return new Rx.Observable((ob) => {
					if (req.body.CatId) {
						accountTitle
							.aggregate([
								{
									$match: {
										CatId: mongoose.Types.ObjectId(req.body.CatId),
									},
								},
							])
							.exec((err, result) => {
								if (err) {
									ob.error(err);
									ob.complete();
								} else {
									ob.next({
										data,
										titles: result.map((mr) => {
											return {
												CreatorId,
												Type: globalVar.TypeOfCatOrTitleStop.TITLE,
												TitleId: mr._id,
												CreateAt,
											};
										}),
									});
									ob.complete();
								}
							});
					} else {
						ob.next(data);
						ob.complete();
					}
				});
			}),
			operators.concatMap((data) => {
				return new Rx.Observable((ob) => {
					if (data.Type == globalVar.TypeOfCatOrTitleStop.TITLE) {
						ob.next({
							titles: [data],
						});
						ob.complete();
					} else {
						accountCatTitleStop.insertMany(data.titles, function (err, result) {
							if (!err) {
								ob.next({
									cat: data.data,
									titles: result.map((mr) => {
										return {
											...mr._doc,
											stop: {
												Type: globalVar.TypeOfCatOrTitleStop.TITLE,
												TitleId: mr._doc._id,
											},
										};
									}),
								});
								ob.complete();
							} else {
								ob.error(err);
								ob.next();
							}
						});
					}
				});
			})
		)
		.subscribe(
			(result) => {
				util.res.success({
					res,
					data: result,
				});
			},
			(err) => {
				util.res.error({
					res,
					msg: err,
				});
			}
		);
});

module.exports = router;
